/*******************************************************************************
 * ShowItemAction.java
 *
 * Created by jigar
 * Last modified Date: Oct 15, 2008 10:39:18 AM by nishan
  * Version : 0.1
 * Copyright (c) 2008 - 2009 cyberThink Infotech Pvt. Ltd., All rights reserved.
 ******************************************************************************/
package com.printeverywhere.action;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.validator.util.ValidatorUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

import com.opensymphony.xwork2.ActionContext;
import com.printeverywhere.delegator.AuctionBidsServiceDelegator;
import com.printeverywhere.delegator.CommonFunctionDelegator;
import com.printeverywhere.delegator.ItemsServiceDelegator;
import com.printeverywhere.delegator.MailServerDelegator;
import com.printeverywhere.dto.CrossPromotion;
import com.printeverywhere.dto.GeneralCategoriesWOS;
import com.printeverywhere.dto.ItemAuctionImage;
import com.printeverywhere.dto.AuctionBids;
import com.printeverywhere.dto.BidStatus;
import com.printeverywhere.dto.ItemCategories;
import com.printeverywhere.dto.ItemOffers;
import com.printeverywhere.dto.Items;
import com.printeverywhere.dto.ItemsWatchlist;
import com.printeverywhere.dto.MailServer;
import com.printeverywhere.dto.MailingSystem;
import com.printeverywhere.dto.User;
import com.printeverywhere.dto.UserAboutMe;
import com.printeverywhere.dto.UserFavoritesUsers;
import com.printeverywhere.dto.UsersInfo;
import com.printeverywhere.util.AdminConstants;
import com.printeverywhere.util.AttributeConstants;
import com.printeverywhere.util.CommonUtil;
import com.printeverywhere.util.DateUtil;
import com.printeverywhere.util.MailHelper;
import com.printeverywhere.util.SearchCriteria;
import com.printeverywhere.util.SessionUtil;
import com.printeverywhere.util.Validator;


public class ShowItemAction extends FrontBaseSupport implements ServletRequestAware {

	/**  */
	private static final long serialVersionUID = 1L;

	private HttpServletRequest request;

	private static final Logger logger = Logger.getLogger(ShowItemAction.class);

	private List<Integer> itemId = new ArrayList<Integer>();

	private List<Items> compareItemList = new ArrayList<Items>();

	private List<ItemOffers> itemOffersList = new ArrayList<ItemOffers>();

	private List<CrossPromotion> crossPromotionList = new ArrayList<CrossPromotion>();

	private AuctionBids auctionBids;

	private Integer askSellerId = 0;

	private Items item;

	private List<ItemAuctionImage> itemAuctionImages;

	private Boolean selfCopy;

	private String questions;

	private String fromPage;

	private String friendEmail;

	private String message;

	private char[] views = new char[] {'0', '0', '0', '0', '0', '0'};

	private final boolean showItem = true;

	private MailServer mailContent = new MailServer();

	private User user;

	private UsersInfo userInfo;

	private UserAboutMe userAboutMe;

	private UsersInfo bidderUserInfo;

	private UserAboutMe bidderUserAboutMe;

	private ItemOffers itemOffers;

	private SearchCriteria searchCriteria = new SearchCriteria();

	private Date currentDate;

	private String[] categoriesName;

	private String[] shipTo;

	/** The file. */
	private File file;

	/** The content type. */
	private String contentType;

    /** The filename. */
    private String filename;

    private boolean favorite;

    private boolean inWatchList;

	public File getUpload() {
		return file;
	}

	public void setUpload(File file) {
		this.file = file;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public boolean isShowItem() {
		return showItem;
	}

	public ShowItemAction() {
		super(true, false);
	}

	public String execute() throws Exception {
		user = SessionUtil.getUser(request);
		if(request.getParameter("cid") != null) {
			askSellerId = Integer.parseInt(request.getParameter("cid"));
			item = ItemsServiceDelegator.getItemsById(askSellerId);
			currentDate = new Date();
		}
		return SUCCESS;
	}

	public String showOfferDetails() throws Exception {
		if(request.getParameter("cid") != null) {
			item = ItemsServiceDelegator.getItemsById(Integer.parseInt(request.getParameter("cid")));

			if (item.getUserId().getId().intValue() != SessionUtil.getUser(request).getId().intValue()) {
				return ERROR;
			} else {
				List<Criterion> criterionList = new ArrayList<Criterion>();
				criterionList.add(Restrictions.eq("items.itemId", item.getItemId()));
				itemOffersList = (List<ItemOffers>) CommonFunctionDelegator.getObjectsByCriterion(criterionList, null, null, ItemOffers.class);

				DynamicTreeSelectAction dynamicTreeSelectAction = new DynamicTreeSelectAction();
				categoriesName = dynamicTreeSelectAction.getGeneralCategoriesFromCategoryId(((ItemCategories) item.getCategories().iterator().next()).getCategoryId().getCategoryId());

				currentDate = new Date();
			}
		}

		return SUCCESS;
	}

	public String printItem() throws Exception {
		setLeftAllowed(false);
		showItem();
		return SUCCESS;
	}

	public String mailItemMessage() throws Exception {
		setLeftAllowed(false);
		String[] mails = friendEmail.split(";");

		for (String mail : mails) {
			if(mail != null && Validator.isMailAddress(mail)) {
				try {
					MailingSystem mailingSystem = (MailingSystem) ActionContext.getContext().getApplication().get(AdminConstants.MAILING_OPTIONS);
					MailHelper mailHelper = new MailHelper(mailingSystem.getServerAddress(), mailingSystem.getServerUsername(), mailingSystem.getServerPassword());

					mailHelper.sendMail(mailingSystem.getWebmasterEmailAddress(), friendEmail, "Auction item", this.message);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				request.getSession().setAttribute("msg", "Please, enter correct email address...");
				return INPUT;
			}
		}

		return SUCCESS;
	}

	public String askQuestionToSeller() throws Exception{
		askSellerId = Integer.parseInt(request.getParameter("item.itemId"));
		item = ItemsServiceDelegator.getItemsById(askSellerId);
		String subject = "Question for seller, Item Nr." + item.getItemId();
		if(questions != null){
			if(selfCopy == true){
				user = SessionUtil.getUser(request);
				this.mailContent.setUserByUserId(user);
				this.mailContent.setUserByFromId(user);
				this.mailContent.setBody(questions);
				this.mailContent.setSubject(subject);
				this.mailContent.setFlag(false);
				this.mailContent.setIsRead(false);
				DateFormat myDate = new SimpleDateFormat("yyyy-MM-dd hh:ss:mm");
				Calendar cal = GregorianCalendar.getInstance();
				cal.add(Calendar.MONDAY, 2);
				String strDate = myDate.format(cal.getTime());
				Date expiresDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:ss:mm").parse(strDate);
				this.mailContent.setExpiresDate(expiresDateFormat);
				MailingSystem mailingSystem = (MailingSystem) ActionContext.getContext().getApplication().get(AdminConstants.MAILING_OPTIONS);
				MailHelper mailHelper = new MailHelper(mailingSystem.getServerAddress(), mailingSystem.getServerUsername(), mailingSystem.getServerPassword());
				mailHelper.sendMail(mailingSystem.getWebmasterEmailAddress(), user.getEmail(), subject , questions);
				MailServerDelegator.insertMail(mailContent);
			}

				user = SessionUtil.getUser(request);
				this.mailContent.setUserByUserId(item.getUserId());
				this.mailContent.setUserByFromId(user);
				this.mailContent.setBody(questions);
				this.mailContent.setSubject(subject);
				this.mailContent.setFlag(false);
				this.mailContent.setIsRead(false);
				DateFormat myDate = new SimpleDateFormat("yyyy-MM-dd hh:ss:mm");
				Calendar cal = GregorianCalendar.getInstance();
				cal.add(Calendar.MONDAY, 2);
				String strDate = myDate.format(cal.getTime());
				Date expiresDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:ss:mm").parse(strDate);
				this.mailContent.setExpiresDate(expiresDateFormat);
				MailingSystem mailingSystem = (MailingSystem) ActionContext.getContext().getApplication().get(AdminConstants.MAILING_OPTIONS);
				MailHelper mailHelper = new MailHelper(mailingSystem.getServerAddress(), mailingSystem.getServerUsername(), mailingSystem.getServerPassword());
				mailHelper.sendMail(mailingSystem.getWebmasterEmailAddress(), item.getUserId().getEmail() , subject , questions);
				MailServerDelegator.insertMail(mailContent);
		}else{
			addActionError("Please insert your question");
			return INPUT;
		}

		return SUCCESS;
	}

	public String showItem() {
		if(request.getParameter("cid") != null) {
			this.item = ItemsServiceDelegator.getItemsById(Integer.parseInt(this.request.getParameter("cid")));

			userInfo = (UsersInfo) CommonFunctionDelegator.getObjectById("user.id", this.item.getUserId().getId(), UsersInfo.class);
			userAboutMe = (UserAboutMe) CommonFunctionDelegator.getObjectById("user.id", this.item.getUserId().getId(), UserAboutMe.class);

			if(this.item.getItemtype().getId() == 1) {
				auctionBids = AuctionBidsServiceDelegator.getMaxBidder(this.item.getItemId());
				bidderUserInfo = (UsersInfo) CommonFunctionDelegator.getObjectById("user.id", this.item.getUserId().getId(), UsersInfo.class);
				bidderUserAboutMe = (UserAboutMe) CommonFunctionDelegator.getObjectById("user.id", this.item.getUserId().getId(), UserAboutMe.class);
			}

			SearchCriteria searchCriteria = new SearchCriteria();
			searchCriteria.setAttribute("id.items", this.item);
			itemAuctionImages = (List<ItemAuctionImage>) CommonFunctionDelegator.getObjectBySearchCriteria(searchCriteria, ItemAuctionImage.class);
			int totalViews = this.item.getViews();
			this.item.setViews(totalViews + 1);
			CommonFunctionDelegator.generalUpdatebyobj(this.item);
			char[] tmpViews = String.valueOf(totalViews).toCharArray();

			for (int index = 0; index < tmpViews.length; index++) {
				this.views[tmpViews.length - index - 1] = tmpViews[index];
			}
			user = SessionUtil.getUser(request);
			searchCriteria.removeAllAttribute();
			searchCriteria.setAttribute(AdminConstants.USER, user);
			crossPromotionList = (List<CrossPromotion>) CommonFunctionDelegator.GeneralgetCriteriaList(CrossPromotion.class.getName(), searchCriteria);
		}
		if(item.getEndTime().before(DateUtil.getTodaysDate())){
			item.setClosed(true);
		}else{
			item.setClosed(false);
		}
		if(request.getParameter("p") != null){
			fromPage = request.getParameter("p");
		}

		populateShipTo(this.item.getShipTo());
		currentDate = new Date();

		return SUCCESS;
	}

	public String confirmAuctionBid(){
		setLeftAllowed(true);
		setRightAllowed(false);
		try{
			user = SessionUtil.getUser(request);
			if(request.getParameter("cid") != null) {
				this.item = ItemsServiceDelegator.getItemsById(Integer.parseInt(this.request.getParameter("cid")));
			}
			Double minBid;
			if(item.getCurrentBid() != null){
				minBid = item.getCurrentBid().doubleValue();
			}else{
				minBid = item.getStartBid() - item.getIncrement();
			}
			if(item.getEndTime().before(DateUtil.getTodaysDate())){
				item.setClosed(true);
			}else{
				item.setClosed(false);
			}
			if(auctionBids.getMaxBid() < minBid){
				addActionError("Your maximum bid per item can not be less than Current bid.");
				fromPage = "createAuction";
				return INPUT;
			}
		}catch (Exception e) {
			fromPage = "createAuction";
			user = SessionUtil.getUser(request);
			return INPUT;
		}
		setLeftAllowed(false);
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	public String addAuctionBid(){
		setLeftAllowed(false);
		setRightAllowed(false);
		try{
			BidStatus bidStatus;
			user = SessionUtil.getUser(request);
			searchCriteria.removeAllAttribute();
			searchCriteria.setAttribute(AdminConstants.ID, 4);
			bidStatus = (BidStatus) (CommonFunctionDelegator.getObjectBySearchCriteria(searchCriteria, BidStatus.class).size() > 0 ?CommonFunctionDelegator.getObjectBySearchCriteria(searchCriteria, BidStatus.class).get(AdminConstants.ZERO_NUMBER) : new BidStatus());
			if(request.getParameter("cid") != null) {
 				this.item = ItemsServiceDelegator.getItemsById(Integer.parseInt(this.request.getParameter("cid")));
			}
			System.out.println(auctionBids.getMaxBid().longValue());
			item.setStartBid(auctionBids.getMaxBid());
			CommonFunctionDelegator.generalUpdatebyobj(this.item);
			ActionContext.getContext().getApplication().put(AttributeConstants.ITEMS, this.item);
			if(item.getEndTime().before(DateUtil.getTodaysDate())){
				item.setClosed(true);
			}else{
				item.setClosed(false);
			}
			auctionBids.setBidStatus(bidStatus);
			auctionBids.setEmail(user.getEmail());
			auctionBids.setItems(item);
			auctionBids.setTime(DateUtil.getTodaysDate().toString());
			auctionBids.setUser(user);
			AuctionBidsServiceDelegator.add(auctionBids);
		}catch (Exception e) {
			return INPUT;
		}
		return SUCCESS;
	}
	public String compareItems() {
		itemId.add(1);
		itemId.add(3);

		for (int i=0;i<itemId.size();i++) {
			Items items = ItemsServiceDelegator.getItemsById(itemId.get(i));
			compareItemList.add(items);
		}
		return SUCCESS;
	}

	public String makeOffer() throws Exception{
		user = SessionUtil.getUser(request);
		if(request.getParameter("fromPage") != null){
			fromPage = request.getParameter("fromPage");
		}
		if(this.file!=null) {
			try{
			if(!CommonUtil.isImage(FileUtils.readFileToByteArray(file))){
				addActionError(getText("struts.messages.error.uploading"));
				return ERROR;
			}
			}catch (Exception e) {
				addActionError(getText("struts.messages.error.uploading"));
				return ERROR;
			}

			this.itemOffers.setImage(FileUtils.readFileToByteArray(file));
		}

		if(request.getParameter("cid") != null) {
			this.item = ItemsServiceDelegator.getItemsById(Integer.parseInt(this.request.getParameter("cid")));
		}

		this.itemOffers.setItems(item);
		this.itemOffers.setUser(user);
		SearchCriteria searchCriteria = new SearchCriteria();
		searchCriteria.removeAllAttribute();
		searchCriteria.setAttribute("id", 4);
		List<BidStatus> list = (List<BidStatus>) CommonFunctionDelegator.GeneralgetCriteriaList(BidStatus.class.getName() , searchCriteria);
		BidStatus status = list.size() > 0 ? list.get(0) : null;
		if(status != null)
		this.itemOffers.setStatus(status);
		CommonFunctionDelegator.generalInsertbyobj(this.itemOffers);

		return SUCCESS;
	}

	/**
	 * @return the itemId
	 */
	public List<Integer> getItemId() {
		return itemId;
	}

	/**
	 * @param itemId the itemId to set
	 */
	public void setItemId(List<Integer> itemId) {
		this.itemId = itemId;
	}

	/**
	 * @return the compareItemList
	 */
	public List<Items> getCompareItemList() {
		return compareItemList;
	}

	/**
	 * @param compareItemList the compareItemList to set
	 */
	public void setCompareItemList(List<Items> compareItemList) {
		this.compareItemList = compareItemList;
	}

	public Items getItem() {
		return item;
	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public char[] getViews() {
		return views;
	}

	public Integer getAskSellerId() {
		return askSellerId;
	}

	public void setAskSellerId(Integer askSellerId) {
		this.askSellerId = askSellerId;
	}

	public void setItem(Items item) {
		this.item = item;
	}

	public Boolean getSelfCopy() {
		return selfCopy;
	}

	public void setSelfCopy(Boolean selfCopy) {
		this.selfCopy = selfCopy;
	}

	public String getQuestions() {
		return questions;
	}

	public void setQuestions(String questions) {
		this.questions = questions;
	}

	public MailServer getMailContent() {
		return mailContent;
	}

	public void setMailContent(MailServer mailContent) {
		this.mailContent = mailContent;
	}

	public List<ItemAuctionImage> getItemAuctionImages() {
		return itemAuctionImages;
	}

	public AuctionBids getAuctionBids() {
		return auctionBids;
	}

	public void setAuctionBids(AuctionBids auctionBids) {
		this.auctionBids = auctionBids;
	}

	public String getFromPage() {
		return fromPage;
	}

	public void setFromPage(String fromPage) {
		this.fromPage = fromPage;
	}

	public ItemOffers getItemOffers() {
		return itemOffers;
	}

	public void setItemOffers(ItemOffers itemOffers) {
		this.itemOffers = itemOffers;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	/**
	 * Sets the upload content type.
	 *
	 * @param contentType the new upload content type
	 */
	public void setUploadContentType(String contentType) {
        this.contentType = contentType;
     }

	/**
	 * Sets the upload file name.
	 *
	 * @param filename the new upload file name
	 */
	public void setUploadFileName(String filename) {
        this.filename = filename;
     }

	public String  getUploadContentType() {
	       return contentType;
	}

	public String getUploadFilename() {
		return filename;
	}

	@Override
	public void validate() {
		super.validate();
		showItem();
	}

	public Date getCurrentDate() {
		return currentDate;
	}

	public UsersInfo getUserInfo() {
		return userInfo;
	}

	public UserAboutMe getUserAboutMe() {
		return userAboutMe;
	}

	public String getFriendEmail() {
		return friendEmail;
	}

	public void setFriendEmail(String friendEmail) {
		this.friendEmail = friendEmail;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public List<ItemOffers> getItemOffersList() {
		return itemOffersList;
	}

	public String[] getCategoriesName() {
		return categoriesName;
	}

	public boolean isFavorite() {
		return favorite;
	}

	public boolean isInWatchList() {
		return inWatchList;
	}

	private void generalSettings(Items item, User user) {
		List<Criterion> criterionList = new ArrayList<Criterion>();
		criterionList.add(Restrictions.eq("user", user));
		criterionList.add(Restrictions.eq("userIdFav", item.getUserId()));

		List list = CommonFunctionDelegator.getObjectsByCriterion(criterionList, null, null, UserFavoritesUsers.class);
		favorite = (list != null && list.size() > 0) ? true : false;

		criterionList.removeAll(criterionList);
		criterionList.add(Restrictions.eq("user", user));
		criterionList.add(Restrictions.eq("items", item));

		list = CommonFunctionDelegator.getObjectsByCriterion(criterionList, null, null, ItemsWatchlist.class);
		inWatchList = (list != null && list.size() > 0) ? true : false;
	}

	private void populateShipTo(String locations) {
		List list = CommonFunctionDelegator.executeSQLQuery("SELECT categoryName FROM location_categories WHERE categoryId IN (" + locations + ")");
		shipTo = new String[(list != null) ?list.size() : 0];
		int index = 0;
		for (Object object : list) {
			this.shipTo[index++] = object.toString();
		}
	}

	public String[] getShipTo() {
		return shipTo;
	}

	public UsersInfo getBidderUserInfo() {
		return bidderUserInfo;
	}

	public UserAboutMe getBidderUserAboutMe() {
		return bidderUserAboutMe;
	}

	public List<CrossPromotion> getCrossPromotionList() {
		return crossPromotionList;
	}

	public void setCrossPromotionList(List<CrossPromotion> crossPromotionList) {
		this.crossPromotionList = crossPromotionList;
	}
}
